<?php

namespace addons\fzdc\controller;

use app\admin\model\fzdc\coupon\Receive;
use app\common\controller\Api;
use app\admin\model\fzdc\coupon\Coupon as Cp;
use think\Cache;

class Coupon extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['couponList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /*
     * 优惠券列表
     */
    public function couponList()
    {
        $user_id = $this->auth->id ?? 0;
        $data = Cp::where('state', 1)
            ->where("deletetime", null)
            ->order("weigh", "desc")
            ->field("id,title,image,with_amount,used_amount,quota,start_time,end_time,draw_range,astrict,remarks")
            ->select()
            ->each(function ($item) use ($user_id) {
                $item->image = cdnurl($item->image, true);
                //查询剩余可领优惠券数量
                $count = Receive::where("coupon_id", $item->id)->count();
                $item->quota = bcsub($item->quota, $count);
                //判断当前时间是否在优惠券领取时间区间
                $draw = explode(' - ', $item->draw_range);
                $item->status = 1;
                $res = Receive::where(["coupon_id" => $item->id, "user_id" => $this->auth->id])->count();
                $flag = true;
                if ($res >= $item->astrict) {
                    $flag = false;
                }
                if (!(time() >= strtotime($draw[0]) && time() <= strtotime($draw[1])) || !$flag) {
                    $item->status = 0;
                }
                if (Receive::get(["user_id" => $user_id, "coupon_id" => $item->id])) {
                    $item->status = 0;
                }
                $item->show = 0;
            });
        foreach ($data as $k => &$v) {
            if ($v['status'] == 0) {
                unset($data[$k]);
            }
        }
        $this->success('返回成功', array_merge($data->toArray()));
    }

    /*
     * 领取优惠券
     */
    public function draw()
    {
        $user_id = $this->auth->id;
        $id = $this->request->post('id');     //优惠券id
        if (!$id) {
            $this->error("请输入优惠券id");
        }
        $coupon = Cp::get($id);
        //判断是否在优惠券领取时间区间
        $draw = explode(' - ', $coupon->draw_range);
        if (time() >= strtotime($draw[0]) && time() <= strtotime($draw[1])) {
            //查询该优惠券限领，判断用户是否符合领取条件
            $count = Receive::where("coupon_id", $coupon->id)->count();
            if ($count >= $coupon->quota) {
                $this->error("该优惠券已领取达到上限");
            }
            //领取优惠券
            Receive::create([
                "user_id" => $user_id,
                "coupon_id" => $coupon->id,
                "money" => $coupon->used_amount,
                "create_time" => time(),
                "state" => 0,
            ]);
            $this->success('领取成功');
        } else {
            $this->error("该优惠券已过可领取时间");
        }

    }

    /*
     * 获取可用优惠券
     */
    public function usable()
    {
        $user_id = $this->auth->id;
        $price = $this->request->post('price');
        if (!$price) {
            $this->error("缺少商品价格");
        }
        //查询优惠券领取记录表
        $data = Receive::where(['state' => '0', 'user_id' => $user_id])->column("coupon_id");
        //更新优惠券状态
        $cp = Cp::whereIn("id", $data)->select();
        foreach ($cp as $cv) {
            if (time() > $cv['end_time']) {
                Receive::where(["user_id" => $user_id, "coupon_id" => $cv['id']])->update(["state" => '-1']);
            }
        }
        $data = Receive::where(['state' => '0', 'user_id' => $user_id])->column("coupon_id");
        $data = Cp::where('state', 1)
            ->where("with_amount", "<=", $price)
            ->where("end_time", ">", time())
            ->whereIn("id", $data)
            ->order("weigh", "desc")
            ->field("id,title,image,with_amount,used_amount,quota,start_time,end_time,draw_range,astrict,remarks")
            ->select();
        foreach ($data as $row) {
            $row->show = 0;
            $row->image = cdnurl($row->image, true);
        }


        $this->success('返回成功', $data);

    }

    /*
     * 我的优惠券列表
     */
    public function list()
    {
        $user_id = $this->auth->id;
        //查询优惠券领取记录表
        $data = Receive
            ::where(['state' => '0', 'user_id' => $user_id])
            ->column("coupon_id");

        $data = Cp::where('state', 1)
            ->whereIn("id", $data)
            ->order("weigh", "desc")
            ->field("id,title,image,with_amount,used_amount,quota,start_time,end_time,draw_range,astrict,remarks")
            ->select()
            ->each(function ($item) {
                $item->image = cdnurl($item->image, true);
                //查询剩余可领优惠券数量
                $count = Receive::where("coupon_id", $item->id)->count();
                $item->quota = bcsub($item->quota, $count);
                //判断当前时间是否在优惠券领取时间区间
                $draw = explode(' - ', $item->draw_range);
                $item->status = 0;
                $res = Receive::where(["coupon_id" => $item->id, "user_id" => $this->auth->id])->count();
                $flag = true;
                if ($res >= $item->astrict) {
                    $flag = false;
                }
                if ((time() >= strtotime($draw[0]) && time() <= strtotime($draw[1])) && $flag) {
                    $item->status = 1;
                }
                $item->show = 0;
            });
        $this->success('返回成功', $data);

        $this->success('返回成功', $data);
    }
}
